﻿/********
* 
* 
*  Description:
*  Create By Kain at 4/6/2011 9:45:05 AM
*  
*
*  Revision History:
*  Date                  Who                 What
*  
* 
*/

#region

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cherry.Agile.Security;
using Cherry.Agile.ServiceModel;
using Cherry.Agile.Core;
using Microsoft.Practices.Unity;

#endregion

namespace Cherry.Agile.ServiceModel.Security
{
    public class TokenProvider : ITokenProvider
    {
        static ITokenProvider _current;// = new TokenProvider();
        static TokenProvider()
        {
            try
            {
                if (_current == null && !Container.Current.IsRegistered<ITokenProvider>())
                {
                    _current = new TokenProvider();
                    Container.Current.RegisterInstance<ITokenProvider>(_current);
                }
                else
                {
                    _current = Container.Current.Resolve<ITokenProvider>();
                }
            }
            catch
            {
                _current = new TokenProvider();
                Container.Current.RegisterInstance<ITokenProvider>(_current);
            }

        }

        public static ITokenProvider Current
        {
            get { return _current; }
        }

        const string __Key = "__token";
        public IToken CreateToken(System.Security.Principal.IIdentity user, bool createPersistent)
        {
            var token = new Token(user as User);
            ApplicationContext.Current[__Key] = token.GetTicketString();
            return token;
        }

        public IToken GetCurrentToken()
        {
            if (ApplicationContext.Current[__Key] == null)
                return null;
            return new Token(ApplicationContext.Current[__Key] as string);
        }

        public void Clear()
        {
            ApplicationContext.Current[__Key] = null;
        }
    }


}
